<?php

namespace App\Console\Commands;

use App\Models\Circle;
use App\Models\Star;
use App\Models\User;
use App\Services\UserWeightService;
use Illuminate\Console\Command;
use YangJiSen\CacheUserProvider\CacheForget;

class CountCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'count';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        \Log::info('-----------user-weight-----------------------------');
        $sql = 'update circles join (select circle_id, count(user_id) as total from user_join_circles group by circle_id
) as ma on circles.id = ma.circle_id set circles.join_count = ma.total';


        User::chunk(100, function ($list) {
            foreach ($list as $user) {
                //计算用户圈子数
                $sql_circle = 'select count(*) as total from `circles` inner join `user_join_circles` on `circles`.`id` = `user_join_circles`.`circle_id` 
and `user_join_circles`.`user_id` = "'.$user->id.'" where `circles`.`is_activity` = "0" and `status` = "2" and `deleted_at` is null  ';
                $res = \DB::select($sql_circle);
                $total = $res[0]->total ?? 0;
                $user->circle_count = $total;

                //计算用户动态数
                $sql_article = 'select count(*) as total from articles where status = 1 and user_id = ' . $user->id;
                $res2 = \DB::select($sql_article);
                $total2 = $res2[0]->total ?? 0;
                $user->article_count = $total2;
                $user->save();
                CacheForget::CacheForget($user);
            }
        });

        //计算圈子动态数
        Circle::chunk(100, function ($list) {
            foreach ($list as $circle) {
                $sql = ' select count(*) as total from `articles` inner join `article_relate_circles` on `articles`.`id` = `article_relate_circles`.`article_id` 
 and `circle_id` in ("'.$circle->id.'") where `status` = "1"';
                $res = \DB::select($sql);
                $total = $res[0]->total ?? 0;
                $circle->feed_count = $total;
                $circle->save();
            }
        });

        \Log::info('-----------end-user-weight-----------------------------');
    }
}
